﻿using System.Xml.Linq;
using System;
using ResxHelper.Object;
using System.IO;

namespace ResxHelper.Logic.Readers
{
    public class ResxResourceFileReader : IResourceFileReader
    {
        public string Path { get; private set; }

        public ResxResourceFileReader(string path)
        {
            Path = path;
        }

        public ResourceFile Read()
        {
            if (!File.Exists(Path)) return null;

            XDocument doc;
            try
            {
                doc = XDocument.Load(Path);
            }
            catch
            {
                throw new FileLoadException(string.Format("The file could not be read (path = {0})", Path));
            }

            var file = new ResourceFile
                {
                    FilePath = Path,
                    CultureInfo = ResourceFile.ReadCulture(Path),
                    Entries = GetEntries(doc)
                };

            return file;
        }

        public static ResourceFileEntryCollection GetEntries(XDocument doc)
        {
            var data = doc.Descendants("data");
            var entries = new ResourceFileEntryCollection();

            // read the entries
            foreach (var xEntry in data)
            {
                var key = xEntry.Attribute("name").Value;
                var xvalue = xEntry.Element("value");
                var xcomment = xEntry.Element("comment");

                var value = xvalue == null ? String.Empty : xvalue.Value;
                var comment = xcomment == null ? String.Empty : xcomment.Value;

                entries.Add(key, new ResourceFileEntry { Key = key, Value = value, Comment = comment });
            }

            return entries;
        } 
    }
}
